<script setup>
import { reactive, ref, onMounted, watch, onBeforeUnmount } from "vue";
import { generateBarcode } from "@/utils/code/code";
import eventBus from "@/utils/eventBus";
const props = defineProps(["tagGraph", "zoomRate", "mmPxRatio", "canvasRatio"]);
let barcodeModel = reactive({
  textType: "manual",
  barcodeType: "code128",
  barcodeTextPosition: "below",
  text: "0123456789",
  dynamicTextNumber: 0,
  dynamicTextIncrement: 1
});
let fontSize = ref(9);
let fontFamily = ref("SimHei");
let width = ref(14.9);
let height = ref(6.1);

const codeOptions = [
  { label: "CODE128", value: "code128" },
  { label: "CODE_93", value: "code93" },
  { label: "CODE_39", value: "code39" },
  { label: "EAN_8", value: "ean8" },
  { label: "EAN_13", value: "ean13" },
  { label: "ITF-14", value: "itf14" },
  { label: "UPC", value: "upca" },
  { label: "CODEABAR", value: "rationalizedCodabar" }
];
const ruleFormRef = ref(null);
const textTypeOptions = [
  {
    label: "手动输入",
    value: "manual"
  },
  {
    label: "序列号",
    value: "sequence"
  }
];
const barcodeTextPositionOptions = [
  {
    label: "顶部",
    value: "above"
  },
  {
    label: "底部",
    value: "below"
  },
  {
    label: "无文字",
    value: "none"
  }
];
//定义条码类型对应的规则 改造一下加上提示信息 以及校验规则
const barcodeTypeRules = {
  code128: {
    regex: /^[0-9a-zA-Z\s\-\.\$\%\*\+\/\:\.]*$/,
    message: "Code128 条码内容只能包含数字、字母和特殊字符"
  },
  code93: {
    regex: /^[0-9a-zA-Z\s\-\.\$\%\*\+\/\:\.]*$/,
    message: "Code93 条码内容只能包含数字、字母和特殊字符"
  },
  code39: {
    regex: /^[0-9a-zA-Z\s\-\.\$\%\*\+\/\:\.]*$/,
    message: "Code39 条码内容只能包含数字、字母和特殊字符"
  },
  ean8: {
    regex: /^[0-9]{7}$/,
    message: "EAN-8 条码内容必须是 7 位数字"
  },
  ean13: {
    regex: /^[0-9]{12}$/,
    message: "EAN-13 条码内容必须是 12 位数字"
  },
  itf14: {
    regex: /^[0-9]{13}$/,
    message: "ITF-14 条码内容必须是 13 位数字"
  },
  upca: {
    regex: /^[0-9]{11}$/,
    message: "UPC-A 条码内容必须是 11 位数字"
  },
  rationalizedCodabar: {
    regex: /^[ABCD][0-9a-dA-D\s\-\.\$\%\*\+\/\:\.]*[ABCD]$/,
    message:
      "CODEABAR 条码内容必须以 A、B、C 或 D 开头和结尾，中间只能包含数字、字母和特殊字符"
  }
};

const formRule = reactive({
  text: [
    { required: true, message: "请填写条码内容", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const { barcodeType } = barcodeModel;
        const { regex, message } = barcodeTypeRules[barcodeType];
        if (!regex.test(value)) {
          callback(new Error(message));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

onMounted(() => {
  // eventBus.on("fontSizeChange", newFontSize => {
  //   fontSize.value = newFontSize;
  //   handleChangeBarCodeData();
  // });
  eventBus.on("fontFarimyChange", newFontFarimy => {
    fontFamily.value = newFontFarimy;
    handleChangeBarCodeData();
  });
  // eventBus.on("fontWidthAndHeightChange", newVal => {
  //   // console.log(newVal.width, width.value, newVal.height, height.value);
  //   //判断数据是否一致
  //   if (newVal.width == width.value && newVal.height == height.value) {
  //     return;
  //   }
  //   console.log(newVal);
  //   width.value = newVal.width;
  //   height.value = newVal.height;
  //   handleChangeBarCodeData();
  // });
});

onBeforeUnmount(() => {
  // eventBus.off("fontSizeChange");
  eventBus.off("fontFarimyChange");
  // eventBus.off("fontWidthAndHeightChange");
});

// const getGenerateBarcode = () => {
//   ruleFormRef.value
//     .validate(valid => {
//       if (valid) {
//         generateBarcode(
//           barcodeModel.barcodeType,
//           barcodeModel.text,
//           barcodeModel.barcodeTextPosition,
//           width.value,
//           height.value,
//           parseInt(Math.round(fontSize.value / 1.764)),
//           fontFamily.value
//         ).then(base64 => {
//           props.tagGraph.setSrc(base64);
//         });
//       }
//     })
//     .catch(err => {
//       console.log(err);
//     });
// };

const handleChangeBarCodeData = () => {
  const activeObject = props.tagGraph.getActiveObject();
  if (activeObject) {
    Object.assign(activeObject, {
      barcodeType: barcodeModel.barcodeType,
      barcodeTextPosition: barcodeModel.barcodeTextPosition,
      text: barcodeModel.text,
      dynamicTextIncrement: barcodeModel.dynamicTextIncrement,
      dynamicTextNumber: barcodeModel.dynamicTextNumber,
      textType: barcodeModel.textType
    });

    ruleFormRef.value.validate(valid => {
      if (valid) {
        generateBarcode(
          barcodeModel.barcodeType,
          barcodeModel.text,
          barcodeModel.barcodeTextPosition,
          fontFamily.value
        ).then(base64 => {
          props.tagGraph.setSrc(base64);
        });
      }
    });
    props.tagGraph.saveState();
    props.tagGraph.canvas.renderAll();
  }
};
// 监听tagGraph的变化
watch(
  () => props.tagGraph,
  async newVal => {
    if (newVal) {
      const activeObject = newVal.getActiveObject();
      if (activeObject) {
        let {
          barcodeType = "code128",
          text = "0123456789",
          barcodeTextPosition = "below",
          dynamicTextIncrement = 1,
          dynamicTextNumber = 0,
          textType = "manual"
        } = activeObject;
        barcodeType = barcodeType.toLowerCase();
        Object.assign(barcodeModel, {
          barcodeType,
          text,
          barcodeTextPosition,
          dynamicTextIncrement,
          dynamicTextNumber,
          textType
        });
        fontFamily.value = activeObject.fontFamily;
      }
    }
  },
  {
    immediate: true
  }
);
</script>

<template>
  <div>
    <el-form
      ref="ruleFormRef"
      label-position="top"
      :model="barcodeModel"
      :rules="formRule"
    >
      <el-form-item label="条形码类型">
        <el-select
          v-model="barcodeModel.barcodeType"
          style="width: 100%"
          @change="handleChangeBarCodeData()"
        >
          <el-option
            v-for="(item, index) in codeOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="条形码位置">
        <el-select
          v-model="barcodeModel.barcodeTextPosition"
          style="width: 100%"
          @change="handleChangeBarCodeData()"
        >
          <el-option
            v-for="(item, index) in barcodeTextPositionOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据类型">
        <el-select
          v-model="barcodeModel.textType"
          style="width: 100%"
          @change="handleChangeBarCodeData()"
        >
          <el-option
            v-for="(item, index) in textTypeOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前内容" prop="text">
        <el-input
          v-model="barcodeModel.text"
          type="textarea"
          @input="handleChangeBarCodeData()"
        />
      </el-form-item>

      <div v-if="barcodeModel.textType == 'sequence'">
        <el-form-item label="变化量">
          <el-input-number
            v-model="barcodeModel.dynamicTextIncrement"
            style="width: 100%"
            @change="handleChangeBarCodeData()"
          />
        </el-form-item>
        <el-form-item label="打印序列号个数">
          <el-input-number
            v-model="barcodeModel.dynamicTextNumber"
            style="width: 100%"
            @change="handleChangeBarCodeData()"
          />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
